package com.zj.mq.demo.service.impl;

import com.zj.mq.demo.entity.Order;
import com.zj.mq.demo.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    List<Order> orderList = new ArrayList<>();

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Order addOrder(Order order) {
        order.setId(orderList.size());
        orderList.add(order);

        sendOrder2Queue(order);

        return order;
    }

    private void sendOrder2Queue(Order order) {
        String message = order.getId() + "";
        Message msg = null;
        try {
            msg = MessageBuilder
                    .withBody(message.getBytes("utf-8"))
                    .build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        rabbitTemplate.send("ex.order", "key.order", msg);
    }

    @Override
    public boolean pay(Integer id) {
        Order order = orderList.get(id);
        if (order.isTimeout()) {
            return false;
        } else {
            order.setPay(true);
            return true;
        }
    }

    @Override
    public boolean timeout(Integer id) {
        Order order = orderList.get(id);
        order.setTimeout(true);
        order.setPay(false);
        return true;
    }

    @Override
    public List<Order> timeoutCancelOrder(String username) {
        return orderList.stream()
                .filter(item -> item.getUserName().equals(username) && item.isTimeout() && !item.isPay())
                .collect(Collectors.toList());
    }

    @Override
    public Order getById(int i) {
        return orderList.get(i);
    }

}
